# -*- coding: utf-8 -*-
import os
from PIL import Image
import pandas as pd
import numpy as np
import sklearn
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score
'''参考网址 http://blog.csdn.net/zhulf0804/article/details/53843323'''

filename = r'E:\workspace\Test\MNIST\mnist\train\0\1.png'

# 方法一
# im = Image.open(filename,'r')
# mtr = np.array(im)
# bb = []
# for item in mtr:
#     bb.extend(list(item))
# df_1 = pd.Series(bb)
# df = pd.DataFrame(df_1.values.reshape(-1, len(bb)))
# df.to_csv('data.csv',index=False,header=False)

def img2vector(filename, label):
    im = Image.open(filename,'r')
    mtr = np.array(im)
    bb = []
    for item in mtr:
        bb.extend(list(item))
    df_1 = pd.Series(bb)
    df = pd.DataFrame(df_1.values.reshape(-1, len(bb)))
    df['label'] = label
    return df
    # df.to_csv('data.csv',index=False,header=False)

train_dir = r'E:\workspace\Test\MNIST\mnist\train'
label_name = os.listdir(train_dir)
m = len(label_name)
num_total = 0
train_data = np.zeros((980, 785), np.int)  # 先构建一个多维数组[因为只有980张图片，每张图片转为数值后是784+1维的label]
for i in range(0, m):
    file_name = os.listdir(train_dir + '\\' + label_name[i]) # 获取train_dir目录下的文件名
    # print i, label_name[i],file_name
    for j in range(0,len(file_name)):
        num_total += 1
        print u'路径', train_dir + '\\' + str(i) + '\\' + file_name[j]
        row = img2vector(train_dir + '\\' + str(i) + '\\' + file_name[j], str(i))
        train_data[num_total-1] = row  # 把每张图像的数值添加到多维中
pd.DataFrame(train_data).to_csv('data.csv', index=False, header=False)



# 方法二
# im = Image.open(filename)
# print im.size
# width,height = im.size
# im = im.convert("L")
# data = im.getdata()
# print data
# print '*'*100
# data = np.matrix(data,dtype='float')/255.0
# new_data = np.reshape(data,(height,width))
# print new_data
#     new_im = Image.fromarray(new_data)
#     # 显示图片
#     new_im.show()

def data_scaler(X_train, X_test):
    '''
    根据scaler对训练集和测试集的特征变量实现标准化（0均值，方差为1）
    :return:
    '''
    scaler = sklearn.preprocessing.StandardScaler().fit(X_train)
    X_train_std = scaler.transform(X_train)
    X_test_std = scaler.transform(X_test)
    return X_train_std,X_test_std,scaler

data = pd.read_csv('data.csv', engine='python')
X = data.iloc[:, 0:-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42)
X_train_std, X_test_std,scaler = data_scaler(X_train,X_test)
clf = svm.SVC(decision_function_shape='ovo')
clf.fit(X_train_std, y_train)
y_pred = clf.predict(X_test_std)
print accuracy_score(y_test, y_pred)



test_path = r'E:\workspace\Test\MNIST\mnist\test\1141.png'
im = Image.open(test_path,'r')
mtr = np.array(im)
bb = []
for item in mtr:
    bb.extend(list(item))
df_1 = pd.Series(bb)
test_x = pd.DataFrame(df_1.values.reshape(-1, len(bb)))
X_std = scaler.transform(test_x)
y_new_pred = clf.predict(X_std)
# print(u'新样本预测的类别', y_new_pred)
print u'新样本预测的类别', y_new_pred